package com.zyj.utils.d3.base;

import com.zyj.utils.d3.entity.Point;

/**
 * 直线工具类
 */
public class LineUtils {
    /**
     * 计算空间两条直线AB、CD的最短间距
     * @param A
     * @param B
     * @param C
     * @param D
     * @return
     */
    public static double computeLineDist(Point A, Point B, Point C, Point D) {
        double d, num, den;
        double x1 = A.x;
        double y1 = A.y;
        double z1 = A.z;
        //AB向量：（m1. n1, p1）
        double m1 = B.x - x1;
        double n1 = B.y - y1;
        double p1 = B.z - z1;
        double x2 = C.x;
        double y2 = C.y;
        double z2 = C.z;
        //CD向量：（m2. n2, p2）
        double m2 = D.x - x2;
        double n2 = D.y - y2;
        double p2 = D.z - z2;
        double a12 = x1 - x2;
        double b12 = y1 - y2;
        double c12 = z1 - z2;
        double cross = crossproduct(m1, n1, p1, m2, n2, p2);
        if (cross != 0) {
            num = ((n1 * p2 - n2 * p1) * a12) + ((p1 * m2 - p2 * m1) * b12) + ((m1 * n2 - m2 * n1) * c12);
            d = Math.abs(num / cross);
        } else {
            double p, q, r;
            p = b12 * p1 - c12 * n1;
            q = c12 * m1 - a12 * p1;
            r = a12 * n1 - b12 * m1;
            num = Math.sqrt((p * p) + (q * q) + (r * r));
            den = Math.sqrt((m1 * m1) + (n1 * n1) + (p1 * p1));
            d = num / den;
        }
        return d;
    }

    /**
     *
     * @param m1
     * @param n1
     * @param p1
     * @param m2
     * @param n2
     * @param p2
     * @return
     */
    public static double crossproduct(double m1, double n1, double p1, double m2, double n2, double p2) {
        double a, b, c;
        a = (n1 * p2) - (n2 * p1);
        b = (p1 * m2) - (p2 * m1);
        c = (m1 * n2) - (m2 * n1);
        double cross = Math.pow(a, 2) + Math.pow(b, 2) + Math.pow(c, 2);
        double crossres = Math.sqrt(cross);
        return crossres;
    }
}
